<?php

namespace GuanChanghu\Library\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use GuanChanghu\Library\Facades\RSA;

/**
 * Class ResponseSign
 * @tag encryption free
 * @package GuanChanghu\Library\Http\Middleware
 */
class ResponseSign
{
    /**
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next): mixed
    {
        $response = $next($request);

        $this->sign($request, $response);

        return $response;
    }

    /**
     * @param Request $request
     * @param JsonResponse $response
     * @return bool
     */
    protected function sign(Request $request, JsonResponse $response): bool
    {
        $responseData = $response->getData(true);

        if (!is_array($responseData)) {
            return false;
        }

        /**
         * $var Route $route
         */
        $route = $request->route();

        if (!($route instanceof Route)) {
            return false;
        }

        $routeName = $route->getName();

        if ($routeName === 'upload') {
            $responseData['sign'] = RSA::client('sign')->sign($responseData);

            $response->setData($responseData);
        } else if ($routeName === 'client') {
            $response->setData([
                'sign' => RSA::client('sign')->sign($responseData),
                'items' => $responseData,
            ]);
        }

        return true;
    }
}
